package com.netty.chapter01.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author zjiajia
 * @date 2024/7/8 11:01
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 接受客户端的请求数据
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 接受客户端的请求数据
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String request = new String(bytes, "utf-8");
        System.out.println("client request is : " + request);

        // response  to  client
        String response = "hello client, this is  server ";

        ByteBuf buffer = ctx.alloc().buffer();

        buffer.writeBytes(request.getBytes());
        // 写入客户端
        ctx.writeAndFlush(buffer);


    }
}
